import { onUnmounted, ref } from 'vue'

// 轮询接口等待
export function useAwaitTask(asyncFn: () => Promise<boolean>, time = 2000, isComponent = true) {
    const timer = ref<NodeJS.Timeout | null>(null)

    function start(isRunFirst = false) {
        stop()
        if (isRunFirst) {
            asyncFn()
        }
        timer.value = setInterval(() => {
            asyncFn().then((ret) => {
                if (ret) {
                    stop()
                }
            })
        }, time)
    }

    function stop() {
        if (timer.value !== null) {
            clearInterval(timer.value)
            timer.value = null
        }
    }

    // 组件或者页面才有这个生命周期
    if (isComponent) {
        onUnmounted(() => {
            stop()
        })
    }

    return {
        start,
        stop,
        timer
    }
}
